package com.itheima.tlias84.aspect;

import com.alibaba.fastjson2.JSONObject;
import com.itheima.tlias84.dto.ReportLogDTO;
import com.itheima.tlias84.entity.Emp;
import com.itheima.tlias84.mapper.EmpMapper;
import com.itheima.tlias84.mapper.LogMapper;
import com.itheima.tlias84.po.ReportLogParam;
import com.itheima.tlias84.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;


@Aspect
@Component
@Slf4j
public class ReportLogServices {

    @Resource
    HttpServletRequest request;
    @Resource
    LogMapper logMapper;
    @Resource
    EmpMapper empMapper;

    @Around("@annotation(com.itheima.tlias84.annotaion.ReportLog)") //自定义注解
    public Object count(ProceedingJoinPoint point) throws Throwable {
        ReportLogDTO repor = new ReportLogDTO();
        //获取操作人 username  password
        String token = request.getHeader("token");
        JSONObject jsonObject = JwtUtil.verifyToken(token);
        //通过 用户名查询员工信息  JSONObject jsonObject = JwtUtil.verifyToken(token); 解析出来的JWt令牌里面 包含了 员工的用户名
        //通过用户名 来查询出来员工信息
        Emp emp = empMapper.selectEmpByUsername((String) jsonObject.get("username"));
        repor.setOperateEmpId(emp.getId());
        repor.setOperateEmpName(emp.getName());
        //获取时间
        LocalDateTime openDateTime = LocalDateTime.now();
        repor.setOperateTime(openDateTime);
        //获取方法参数
        Object[] args = point.getArgs();
        repor.setMethodParams(Arrays.toString(args));
        //获取类名对象
        Object target = point.getTarget();
        repor.setClassName(target.getClass().getSimpleName());
        //获取方法名
        String methodName = point.getSignature().getName();
        repor.setMethodParams(methodName);
        //计算时间
        long l = System.currentTimeMillis();
        Object proceed = point.proceed();
        long end = System.currentTimeMillis()-l;
        repor.setCostTime(end);
        //将数值返回
        logMapper.insertLog(repor);
        log.info("操作日志：{}",methodName);
        log.info("执行时间：{}",end);
        log.info("获取方法参数{}",args);
        log.info("获取类名对象{}",target);
        log.info("获取方法名{}",methodName);
        return proceed;
    }
}
